<template>
    <div class="container" v-loading="loading">
        <el-form ref="formRef" :model="form" label-width="150px">
            <el-form-item label="标题" required>
                <el-input v-model="form.title" />
            </el-form-item>
            <el-form-item label="摘要" required>
                <el-input :autosize="{ minRows: 4 }" type="textarea" v-model="form.abstracts" />
            </el-form-item>
            <el-form-item label="图片链接">
                <!-- <el-input v-model="form.image_url" /> -->
                <!-- <el-autocomplete
                    v-model="form.image_url"
                    :fetch-suggestions="queryImageSuggestions"
                    clearable
                    @select="handleSelect"
                /> -->
            </el-form-item>
            <el-form-item label="活动时间" required>
                <el-date-picker
                    v-model="form.activity_time"
                    type="datetime"
                    value-format="YYYY/MM/DD hh:mm:ss"
                    placeholder="请选择活动时间"
                />
            </el-form-item>
            <el-form-item label="活动链接">
                <el-input v-model="form.activity_url" placeholder="外部活动链接时添加" />
            </el-form-item>

            <el-form-item label="活动内容">
                <Editor
                    :autofocus="true"
                    v-model="form.description"
                    placeholder="内部撰写活动时填写"
                    :disabled-menus="[]"
                    @upload-image="handleUploadImage"
                >
                </Editor>
            </el-form-item>
            <el-form-item class="form-tip">
                <span>注：活动链接和活动内容不能同时为空！</span>
            </el-form-item>
            <el-form-item>
                <el-button type="default" @click="handleSubmit(false)">存草稿</el-button>
                <el-button type="default" @click="handleSubmit(false, true)">保存并预览</el-button>
                <el-button type="primary" @click="handleSubmit(true)">发布</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect } from "vue";
import { FormInstance } from "element-plus";
import Editor from "@/components/Editor.vue";
// import {
//     publishAnnouncement,
//     getAnnouncement,
//     uploadAnnouncementImg,
//     AnouncementForm,
// } from "../../api/announcementApi";
// import { queryImageSuggestions } from "../../utils/common";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";

const router = useRouter();
const route = useRoute();
const id = ref<number>();

const formRef = ref<FormInstance>();
const form = reactive<any>({
    title: "",
    abstracts: "",
    image_url: "",
    activity_time: "",
    activity_url: "",
    description: "",
});

const isEdit = route.path === "/announcement/edit";
const loading = ref(false);

// 初始化数据
const initData = async () => {
    if (!isEdit) return;
    if (route.path !== "/announcement/edit") return;
    const idVal = parseInt(route.query.id as string);
    if (idVal === id.value) return;
    id.value = idVal;
    if (formRef.value) {
        formRef.value.resetFields();
    }
    try {
        loading.value = true;
        // const res = await getAnnouncement(id.value);
        // const keys = Object.keys(form);
        // keys.forEach((key) => {
        //     form[key] = res[key];
        // });
    } catch {
        ElMessage.error("获取数据失败");
    } finally {
        loading.value = false;
    }
};
watchEffect(() => {
    initData();
});

const afterSave = (url: string, isPublish = false, isPreview = false) => {
    if (isPublish) {
    } else if (isPreview) {
        window.open(url, "_blank");
    }
};

// 存草稿or预览or发布
const handleSubmit = async (isPublish = false, isPreview = false) => {
    // 表单校验
    if (!formRef.value) return;
    if (await formRef.value.validate()) {
        // 处理图片内容
        const params = { ...form, status: 0, id: id.value };
        let msg = "保存";
        if (isPublish) {
            params.status = 1;
            msg = "发布";
        }
        if (!params.activity_url && !params.description) {
            ElMessage.error("活动链接和活动内容不能同时为空！");
            return;
        }

        try {
            // const res = await publishAnnouncement(params);
            // id.value = res.id;
            ElMessage.success(`${msg}成功`);
            // afterSave(res.url, isPublish, isPreview);
        } catch (e) {
            ElMessage.error(e || `${msg}失败`);
        }
    }
};

// files：表示拖入的图片文件，可以是多个，也可以是一个
// insertImage：url就表示需要回显的地址；desc就是名称；markdown语法：![desc](url)
const handleUploadImage = async (event, insertImage, files) => {
    for (const i in files) {
        const formData = new FormData();
        formData.append("file", files[i]);
        // const imageUrl = await uploadAnnouncementImg(formData);
        // insertImage({
        //     url: imageUrl,
        //     desc: "DESC",
        // });
    }
};
const handleSelect = (item) => {
    form.image_url = item.url;
    console.log(item);
};
</script>

<style lang="scss" scoped>
.container {
    .el-form {
        width: 1000px;
        :deep(.v-md-editor) {
            height: 400px;
        }
        :deep(.el-autocomplete) {
            width: 100%;
        }
    }
    .form-tip {
        font-size: 12px;
        color: #9c9ea3;
        margin-top: -10px;
    }
}
</style>
